package com.allenkerr.service.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import com.allenkerr.dao.TodoRepository;
import com.allenkerr.model.Todo;
import com.allenkerr.service.TodoService;
import com.allenkerr.vo.Result;

/**
 * Created by 小柯 on 2017/10/16.
 */
@Service
public class TodoServiceImpl implements TodoService {

  @Autowired
  private TodoRepository todoDao;

  @Override
  public Result<List<Todo>> listTodos() {
    List<Todo> todos = todoDao.findAll();
    return Result.success(todos);
  }

  @Override
  public Result<List<Todo>> addTodo(String task) {
    if (StringUtils.isBlank(task)) {
      return Result.fail("参数有误！");
    }
    Todo todo = new Todo(task.trim(), false);
    Todo savedTodo = todoDao.saveOne(todo);
    return savedTodo != null ? this.listTodos() : Result.fail("添加失败！");
  }

  @Override
  public Result deleteTodo(Long id) {
    todoDao.delete(id);
    return Result.success();
  }

  @Override
  public Result changeTodo(Todo todo) {
    //Query
    Criteria criteria = Criteria.where("id").is(todo.getId());
    Query query = Query.query(criteria);

    //Update
    Update update = null;
    if (StringUtils.isNotBlank(todo.getTask())) {
      update = Update.update("task", todo.getTask());
    } else if (todo.getDone() != null) {
      update = Update.update("done", todo.getDone());
    } else {
      return Result.fail("参数有误！");
    }

    return todoDao.update(query, update) == 1 ? Result.success() : Result.fail("更新失败！");
  }
}
